package com.luxiu.extensionlib.base

import androidx.fragment.app.Fragment
import android.content.Context
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.viewbinding.ViewBinding
import kotlin.reflect.KClass

abstract class BaseFragment<T : ViewBinding>(private val bindingClass: KClass<T>) : Fragment() {

    protected lateinit var mContext: Context
    lateinit var mBinding: T


    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?,
    ): View? {
        // 由于我们已经有了binding，所以这里不需要inflater来创建视图
        // 但我们仍然需要返回一个非null的View给Fragment系统
        return mBinding.root
    }

    @Suppress("UNCHECKED_CAST")
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        val inflater = LayoutInflater.from(requireContext())
        mBinding =
            bindingClass.java.getDeclaredMethod("inflate", LayoutInflater::class.java, ViewGroup::class.java, Boolean::class.java)
                .invoke(null, inflater, null, false) as T
        mContext = requireContext()
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        initBinding(view)
        initObserver()
        initView()
    }

    abstract fun initBinding(view: View)

    abstract fun initObserver()

    abstract fun initView()

}